import React, { Component } from 'react'
import axios from 'axios'
import Com from '../../../common/common'
import './sass/batch-list.scss'

import store from '../../../redux'
import Api from '../../../config/api'

import Button from 'antd/lib/button'
import Navbar from '../../../Component/navbar'

import Table from 'antd/lib/table'
import Form from 'antd/lib/form'
import Input from 'antd/lib/input'
import Spin from 'antd/lib/spin'
import Icon from 'antd/lib/icon'
import message from 'antd/lib/message'
import DatePicker from 'antd/lib/date-picker'
import Popconfirm from 'antd/lib/popconfirm'
import Modal from 'antd/lib/modal'
import List from 'antd/lib/list'

import moment from 'moment';
import 'moment/locale/zh-cn';
moment.locale('zh-cn');

axios.defaults.withCredentials = true;

const confirm = Modal.confirm;
const FormItem = Form.Item;
const antIcon = <Icon type="loading" style={{ fontSize: 24, marginTop: 200 }} spin />;

let oper = null;

class OperBar extends Component {
    constructor(props) {
        super(props);
        this.state = {
            startDate: '',
            endDate: '',
            startMonent: null,
            endMoment: null,
            selectionNum: 0
        }
    }
    componentWillReceiveProps(nextprops) {
        this.setState({
            selectionNum: nextprops.selectionNum
        })
    }
    componentDidMount() {
        this.search()
    }
    getTime(type, moment, time) {
        if (type === 'start') {
            this.setState({
                startDate: time,
                startMoment: moment
            })
        }
        else {
            this.setState({
                endDate: time,
                endMoment: moment
            })
        }
    }
    disabledstartTime(current) {
        if (this.state.endMoment) {
            return current > this.state.endMoment
        }
        else {
            return false
        }
    }
    disabledendTime(current) {
        if (this.state.startMoment) {
            return current < this.state.startMoment
        }
        else {
            return false
        }
    }
    search() {
        let obj = {
            messageId: this.messageIdInput.input.value,
            account: this.accountInput.input.value,
            accessNumber: this.accessNumberInput.input.value,
            phone: this.phoneInput.input.value,
            startTime: this.state.startDate,
            endTime: this.state.endDate
        }
        this.props.search(obj)
    }
    pushMsg() {
        this.props.pushMsg();
    }
    render() {
        return (
            <Navbar ref={(item) => {oper=item}}>
                <Form layout="inline">
                    <FormItem label="消息编号"><Input style={{ width: '120px' }} ref={(input) => { this.messageIdInput = input }} /></FormItem>
                    <FormItem label="接入号"><Input style={{ width: '120px' }} ref={(input) => { this.accessNumberInput = input }} /></FormItem>
                    <FormItem label="账号"><Input style={{ width: '120px' }} ref={(input) => { this.accountInput = input }} /></FormItem>
                    <FormItem label="上行号码"><Input style={{ width: '120px' }} ref={(input) => { this.phoneInput = input }} /></FormItem>
                    <FormItem label="开始时间">
                        <DatePicker format="YYYY-MM-DD" disabledDate={this.disabledstartTime.bind(this)} onChange={this.getTime.bind(this, 'start')} />
                    </FormItem>
                    <FormItem label="结束时间">
                        <DatePicker format="YYYY-MM-DD" disabledDate={this.disabledendTime.bind(this)} onChange={this.getTime.bind(this, 'end')} />
                    </FormItem>
                    <FormItem>
                        <Button type="primary" icon="search" onClick={this.search.bind(this)}>查询</Button>
                        <Button type="primary" icon="to-top" style={{ marginLeft: '10px' }} onClick={this.pushMsg.bind(this)}>{this.state.selectionNum ? `推送(${this.state.selectionNum})` : '推送'}</Button>
                    </FormItem>
                </Form>
            </Navbar>
        )
    }
}

class Table1 extends Component {
    constructor(props) {
        super(props)
        this.state = {
            dataNum: 0,
            tableHeight: 300,
            tableData: this.props.tableData,
            currentPage: 1,
            selectionShow: false,
            selectKeys: []
        }
    }
    componentDidMount() {
        setTimeout(() => {
            let operbarHeight = oper.box.offsetHeight + 10 + 10;
            this.setState({
                tableHeight: store.getState().mainTableSize - operbarHeight - 45 - 33 - 71 - 15 - 30
            })
            this.unscribe = store.subscribe(this.fullTable.bind(this))
        }, 100)
    }
    componentWillReceiveProps(nextProps) {
        this.setState({
            tableData: nextProps.tableData,
            dataNum: nextProps.dataNum,
            currntPage: nextProps.currentPage,
            selectionShow: nextProps.selectShow
        })
        if (nextProps.resetSelectionFlag) {
            this.resetSelection()
        }
    }
    componentWillUnmount() {
        this.unscribe()
    }
    fullTable() {
        let operbarHeight = oper.box.offsetHeight + 10 + 10;
        this.setState({
            tableHeight: store.getState().mainTableSize - operbarHeight - 45 - 33 - 71 - 15 - 30
        })
    }
    selectTable(keys, items) {
        let ids = '';
        let idsArr = [];
        let num = items.length;
        this.setState({
            selectKeys: keys
        })
        items.forEach((item) => {
            idsArr.push(item.id);
        })
        ids = idsArr.join(',')
        this.props.setSelection(ids, num);
    }
    resetSelection() {
        this.setState({
            selectKeys: []
        })
        this.selectTable([], []);
    }
    render() {
        const columns = [
            { title: 'ID', dataIndex: 'id', key: '1', width: 100 },
            { title: '消息编号', dataIndex: 'messageId', key: '2', width: 220 },
            {
                title: '接入号', key: '3', width: 220, render: (record) => {
                    return (
                        <Popconfirm overlayClassName='no-cancel-pop' placement="top" title={record.accessNumber}>
                            <a>{record.accessNumberAbb}</a>
                        </Popconfirm>
                    )
                }
            },
            { title: '账号', dataIndex: 'account', key: '4', width: 220 },
            { title: '上行号码', dataIndex: 'phone', key: '5', width: 150 },
            {
                title: '上行内容', key: '6', width: 300, render: (record) => {
                    return (
                        <Popconfirm overlayClassName='no-cancel-pop' placement="top" title={record.content}>
                            <a>{record.contentAbb}</a>
                        </Popconfirm>
                    )
                }
            },
            { title: '上行时间', dataIndex: 'createTime', key: '7', width: 200 }
        ];
        return (
            <div className="common-table">
                <Table title={(data) => { return '上行列表' }} rowSelection={{ fixed: true, onChange: this.selectTable.bind(this), selectedRowKeys: this.state.selectKeys }} columns={columns} dataSource={this.state.tableData} pagination={{
                    onChange: this.props.changePage,
                    onShowSizeChange: this.props.changePageSize,
                    defaultPageSize: 20,
                    pageSizeOptions: ['20', '50', '100'],
                    showSizeChanger: true,
                    showQuickJumper: true,
                    current: this.state.currntPage,
                    total: this.state.dataNum,
                    showTotal: total => `共 ${total} 条数据`
                }} scroll={{ x: 1600, y: this.state.tableHeight }}></Table>
            </div>
        )
    }
}

class Box extends Component {
    constructor(props) {
        super(props)
        this.state = {
            loading: true,
            loading2: false,
            tableData: [],
            searchParams: {},
            totalNum: 0,
            paginationData: {
                current: 1,
                pageNum: 1,
                pageSize: 20
            },
            currentPage: 1,
            selectShow: false,
            selectionIds: '',
            showModal: false,
            selectionNum: '',
            feedData: [],
            resetSelectionFlag: false
        }
    }
    setParams(obj) {
        this.setState({
            searchParams: obj
        }, () => {
            this.search('btn');
        })
    }
    search(type) {
        let data = JSON.parse(JSON.stringify(this.state.searchParams));
        if (type === 'btn') {
            data.pageNum = 1;
            this.setState({
                currentPage: 1
            })
        } else {
            data.pageNum = this.state.paginationData.pageNum;
        }
        data.pageSize = this.state.paginationData.pageSize;
        this.setState({
            loading: true,
        })
        axios.post(Api['queryUpMessage'], data).then((res) => {
            if (res) {
                let data = JSON.parse(JSON.stringify(res.data));
                data.list.forEach((item, index) => {
                    item.key = index;
                    item.accessNumberAbb = Com.abbrData(item.accessNumber, 20);
                    item.contentAbb = Com.abbrData(item.content, 20);
                })
                this.setState({
                    loading: false,
                    tableData: data.list,
                    totalNum: data.total,
                    resetSelectionFlag: true
                }, () => {
                    this.setState({
                        resetSelectionFlag: false
                    })
                })
            }
        }).catch((error) => {
            console.log(error)
        })
    }
    changePageSize(current, size) {
        let pagination = JSON.parse(JSON.stringify(this.state.paginationData))
        pagination.pageNum = current;
        pagination.pageSize = size;
        this.setState({
            paginationData: pagination,
            currentPage: current
        }, () => { this.search('pag') })
    }
    changePage(pageNum, pageSize) {
        let pagination = JSON.parse(JSON.stringify(this.state.paginationData))
        pagination.pageNum = pageNum;
        pagination.pageSize = pageSize;
        this.setState({
            paginationData: pagination,
            currentPage: pageNum
        }, () => { this.search('pag') })
    }
    selectToggle(flag) {
        this.setState({
            selectShow: flag
        })
    }
    setSelection(selectionIds, selectionNum) {
        this.setState({
            selectionIds,
            selectionNum
        })
    }
    pushSelections() {
        if (this.state.selectionIds) {
            let that = this;
            confirm({
                title: '推送',
                content: `您确定要推送这${this.state.selectionNum}条上行短信么？`,
                okText: '确定',
                okType: 'confirm',
                cancelText: '取消',
                onOk() {
                    that.setState({
                        loading2: true
                    })
                    axios.post(Api['pushReceiveMessage'] + '?ids=' + that.state.selectionIds).then((res) => {
                        if (res) {
                            that.setState({
                                loading2: false,
                                feedData: res.data
                            }, () => {
                                that.setState({
                                    showModal: true
                                })
                                that.setState({
                                    resetSelectionFlag: true
                                }, () => {
                                    that.setState({
                                        resetSelectionFlag: false
                                    })
                                })
                            })
                        }
                    }).catch((error) => {
                        console.log(error)
                    })
                },
                onCancel() { },
            });
        }
        else {
            message.info('请至少选择一条');
        }
    }
    hideModal() {
        this.setState({
            showModal: false
        })
    }
    render() {
        return (
            <div>
                <Spin size="large" spinning={this.state.loading2}>
                    <OperBar search={this.setParams.bind(this)} selectionNum={this.state.selectionNum} pushMsg={this.pushSelections.bind(this)} />
                    <Spin spinning={this.state.loading} indicator={antIcon}>
                        <Table1
                            currentPage={this.state.currentPage}
                            tableData={this.state.tableData}
                            dataNum={this.state.totalNum}
                            changePageSize={this.changePageSize.bind(this)}
                            changePage={this.changePage.bind(this)}
                            selectShow={this.state.selectShow}
                            setSelection={this.setSelection.bind(this)}
                            resetSelectionFlag={this.state.resetSelectionFlag}
                        />
                    </Spin>
                </Spin>
                <Modal visible={this.state.showModal} onCancel={this.hideModal.bind(this)} title="推送结果" footer={[
                    <Button key="cancel" type="danger" onClick={this.hideModal.bind(this)}>关闭</Button>
                ]} >
                    <List
                        itemLayout="horizontal"
                        dataSource={this.state.feedData}
                        renderItem={item => (
                            <List.Item>
                                <List.Item.Meta
                                    avatar={item.desc.toLowerCase() === "success" ? <Icon type="check-circle-o" style={{ color: 'green', fontSize: '20px' }} /> : <Icon type="close-circle-o" style={{ color: 'red', fontSize: '20px' }} />}
                                    title={'id:' + item.id}
                                    description={item.desc}
                                />
                            </List.Item>
                        )}
                    />
                </Modal>
            </div >
        )
    }
}

export default Box